<!--
 * @Author: lg
 * @Date: 2024-05-25 16:54:51
 * @LastEditors: lg
 * @LastEditTime: 2024-05-29 18:18:36
 * @Description: 
 * @FilePath: \lg-bi\src\views\design-center\components\data-set\index.vue
-->
<!-- 数据集 -->

<template>
  <div class="">
    <el-form
      ref="formRef"
      :model="formData"
      label-width="auto"
      label-position="left"
      :rules="rules"
    >
      <el-form-item label="数据集名称:" prop="dataSetName">
        <el-input v-model.trim="formData.dataSetName" />
      </el-form-item>
      <el-form-item label="选择数据源:" prop="dataSource">
        <el-select v-model="formData.dataSource" placeholder="" value-key="url">
          <el-option
            v-for="item in mockDataSourceList"
            :label="item.label"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="过滤语句:" prop="sql">
        <el-input v-model.trim="formData.sql" type="textarea" />
      </el-form-item>
      <el-form-item label="刷新:">
        <el-button
          type="primary"
          :icon="Search"
          @click="handleUpdate"
          title="展示过滤后的数据"
        ></el-button>
      </el-form-item>
      <json-viewer
        :expand-depth="5"
        copyable
        boxed
        sort
        theme="my-json-theme"
        :value="formData.sqlGetData && JSON.parse(formData.sqlGetData)"
      ></json-viewer>
    </el-form>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { ref } from "vue";
import { rules } from "./constants.js";
import { addSourcesApi } from "@/views/design-center/api/data-set";
import axios from "axios";
const formData = ref({
  sql: "$",
});
// mock的几个数据源
const mockDataSourceList = ref([
  {
    label: "JSON数据源一",
    url: "https://erp-api.gggjpg.com:7777/pds/datereport/workOrderReport/getWorkshopPersonConditionList",
    requestType: "post",
    requestSendData:
      '{"departmentId":"220513C02X225TXP","statisticsTime":"2024-05-25"}',
  },
  {
    label: "JSON数据源二 ",
    url: "www.baidu.com",
    requestType: "get",
    requestSendData: "",
  },
]);

/**
 * @description: 根据过滤语句过滤数据
 * @param {*} value
 * @param {*} propertyPath
 * @return {*}
 */
const getNestedPropertyValue = (value, propertyPath) => {
  if (propertyPath === "$") {
    return value;
  }
  if (propertyPath === "$.") {
    throw new Error("语法错误 ");
  }
  if (propertyPath?.length > 2) {
    // const properties = propertyPath.split('.');
    const properties = propertyPath.slice(2).split(".");
    for (const prop of properties) {
      if (value.hasOwnProperty(prop)) {
        value = value[prop];
      } else {
        return undefined; // 属性不存在，返回 undefined 或者可以根据实际需求进行处理
      }
    }
    return value;
  }
};

//获取动态接口请求的数据
const dyGetData = async () => {
  try {
    let res;
    const headers = {
      token: "a238eeaf3b5c44ddb7317310b333068f",
      "X-Api-Version": "1.0.1",
      "Client-Type": "pc",
    };
    if (formData.value.dataSource.requestType === "get") {
      res = await axios.get(formData.value.dataSource.url, {
        // params: { ...formData.dataSource.requestSendData }
      });
    } else {
      res = await axios.post(
        formData.value.dataSource.url,
        {
          ...JSON.parse(formData.value.dataSource.requestSendData),
        },
        { headers: headers }
      );
    }

    formData.value.sqlGetData = JSON.stringify(
      getNestedPropertyValue(res.data, formData.value.sql)
    );
    console.log(
      "    formData.value.sqlGetData-----",
      formData.value.sqlGetData,
      getNestedPropertyValue(res.data, formData.value.sql)
    );
  } catch (error) {
    console.log("动态接口请求报错", error);
  }
};
const handleUpdate = () => {
  dyGetData();
};
const formRef = ref(null);
/**
 * @description: 提交数据
 * @param {*} value
 * @param {*} propertyPath
 * @return {*}
 */
const submit = async () => {
  const validate = await formRef.value.validate().catch((err) => false);
  if (!validate) return false;
  try {
    const res = await addSourcesApi();
  } catch (error) {}
};
defineExpose({
  submit,
});
</script>
<style scoped lang="scss">
:deep(.jv-container .jv-code.boxed) {
  max-height: 500px;
}

:deep(.jv-my-json-theme .jv-key) {
  color: brown;
}

:deep(.jv-my-json-theme .jv-string) {
  color: #50a14f;
}
</style>
